package day01;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Author Stringzhua
 * @Date 2024/10/28 15:45
 * description:Callable接口
 */
public class Test04 {
    public static void main(String[] args) {
        //计算1~100累加和
        CallTask callTask1 = new CallTask(1, 50);
        CallTask callTask2 = new CallTask(51, 100);

        /**
         * public interface RunnableFuture<V> extends Runnable, Future<V> {}
         *
         * public class FutureTask<V> implements RunnableFuture<V> {
         *     private Callable<V> callable;
         *     public FutureTask(Runnable runnable, V result) {
         *         this.callable = Executors.callable(runnable, result);
         *         this.state = NEW;       // ensure visibility of callable
         *     }
         * }
         */
        //Callable--->FutureTask(Runnable接口的实现类)
        FutureTask<Integer> futureTask1 = new FutureTask<Integer>(callTask1);
        FutureTask<Integer> futureTask2 = new FutureTask<Integer>(callTask2);

        //创建子线程
        Thread thread1 = new Thread(futureTask1);
        Thread thread2 = new Thread(futureTask2);

        //启动子线程
        thread1.start();
        thread2.start();

        //获取各个子线程执行结果【阻塞执行】
        try {
            Integer result1 = futureTask1.get();
            Integer result2 = futureTask2.get();
            Integer sum = result1 + result2;
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

/**
 * @FunctionalInterface public interface Callable<V> {
 * V call()throws Exception;
 * }
 */

//子线程指定区间求和
class CallTask implements Callable<Integer> {
    private int start;
    private int end;

    public CallTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public Integer call() throws Exception {
        int result = 0;
        for (int i = start; i <= end; i++) {
            result += i;
        }
        return result;
    }
}
